package com.edu.lwh.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.Claims;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.edu.lwh.UserFeign;
import com.edu.lwh.pojo.ThreadLocalUtil;
import com.edu.lwh.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ThemeResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.event.CaretListener;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Resource
    private UserFeign userFeign;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return false;
        }
        Claims claims = this.userFeign.parseJwt(token);
        if(ObjectUtil.isEmpty(claims)){
            return false;
        }

        Integer userId = (Integer) claims.getClaim("userId");
        String  userName = (String) claims.getClaim("userName");

        ThreadLocalUtil.set(User.builder()
                .uid(userId)
                .username(userName)
                .build());
        return true;
    }
}
